﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using XQ.WeChatOfficialAccount.DAL.Models;
using XQ.WeChatOfficialAccount.WebAPI.Models;

namespace XQ.WeChatOfficialAccount.WebAPI.Common
{
    /// <summary>
    /// 安全验证类
    /// </summary>
    public class TokenHelper
    {
        /// <summary>
        /// 根据用户ID生成Token
        /// </summary>
        public static string CreateToken(int uid, int? departmentId, int roleId)
        {
            string tokenKey = uid + "|" + departmentId + "|" + roleId + "|" + DateTime.Now.AddHours(1).Ticks;
            return ConvertToBase65(tokenKey);
        }

        /// <summary>
        /// 解密Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static TokenModel DecryptToken(string token)
        {
            TokenModel tokenModel = new TokenModel();
            try
            {
                string tokenValue = Base65Decrypt(token);
                string[] tv = tokenValue.Split('|');
                tokenModel.UID = int.Parse(tv[0]);
                tokenModel.DepartmentID = int.Parse(tv[1]);
                tokenModel.RoleId = int.Parse(tv[2]);
                tokenModel.Timeout = long.Parse(tv[3]);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("解析Token出错", ex);
            }
            return tokenModel;
        }

        /// <summary>
        /// 从请求头信息中获取并解密Token
        /// </summary>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static TokenModel GetTokenByHeaders(HttpRequestHeaders headers)
        {
            //获取用户信息
            TokenModel token = new TokenModel();
            //获取用户信息
            var authorization = headers.Authorization;
            if (authorization != null)
            {
                if (authorization.Scheme == "Bearer")
                {
                    string tokenStr = authorization.Parameter;
                    token = TokenHelper.DecryptToken(tokenStr);
                }
            }

            return token;
        }


        #region 辅助功能
        /// <summary>
        /// base64基础上再做加密
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string ConvertToBase65(string value)
        {
            string base65 = string.Empty;
            byte[] bytes = Encoding.UTF8.GetBytes(value);
            string base64 = Convert.ToBase64String(bytes);
            Random ran = new Random();
            base65 = base64.Insert(3, ran.Next(0, 9).ToString());
            base65 = base65.Insert(2, ran.Next(0, 9).ToString());
            base65 = base65.Insert(1, ran.Next(0, 9).ToString());

            return base65;
        }

        /// <summary>
        /// Base65解密
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string Base65Decrypt(string value)
        {
            string reVal = string.Empty;
            if (!string.IsNullOrEmpty(value))
            {
                byte[] bytes = Convert.FromBase64String(value.Remove(1, 1).Remove(2, 1).Remove(3, 1));
                reVal = System.Text.Encoding.UTF8.GetString(bytes);
            }

            return reVal;
        }

        #endregion
    }
}